#pragma once

// 网络四件套，很网络相关一定要这四个库
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
// 其他库函数
#include <iostream>
#include <unistd.h>
#include <cstdio>
#include <cstring>
#include <string>
#include <cerrno>
#include <cassert>
#include <cstdlib>
#include <thread>
#include <pthread.h>
#include<ctype.h>

using namespace std;

typedef struct sockaddr sockaddr;
typedef struct sockaddr_in sockaddr_in;

class Sock
{
public:
    const int gbacklog=20;
public:
    Sock() {}
    int Socket()
    {
        int listenSock=socket(AF_INET,SOCK_STREAM,0);
        if(listenSock<0)
        {
            cerr<<"socket false "<<endl;
            exit(2);
        }
        cout<<"socket success:"<<listenSock<<endl;
        return listenSock;
    }
    void Bind(int sock,string ip,uint16_t port)
    {
        sockaddr_in addr;
        socklen_t len=sizeof(addr);
        memset(&addr,0,sizeof(addr));
        addr.sin_family=AF_INET;
        addr.sin_port=htons(port);
        addr.sin_addr.s_addr=inet_addr(ip.c_str());
        if(bind(sock,(sockaddr*)&addr,len)<0)//bind( )
        {
            perror("bind");
            exit(3);
        }
    }
    void Listen(int sock)
    {
        if(listen(sock,gbacklog)<0)
        {
            perror("listen");
            exit(4);
        }
        cout<<"listen success"<<endl;
    }
    //const string & 输入形参数
    //string * 输出型参数
    //string & 输入输出型参数
    int Accept(int listenSock,string* ip,uint16_t* port)
    {
        sockaddr_in src;
        socklen_t len=sizeof(src);
        int serviceSock=accept(listenSock,(sockaddr*)&src,&len);//accept(&)
        if(serviceSock<0)
        {
            perror("accept");
            exit(5);
        }
        if(port) *port=ntohs(src.sin_port);
        if(ip)*ip=inet_ntoa(src.sin_addr);
        return serviceSock;
    }
    bool Connect(int sock,const string& ip,const uint16_t& port)
    {
        sockaddr_in server;
        memset(&server,0,sizeof(server));
        server.sin_family=AF_INET;
        server.sin_port=htons(port);
        server.sin_addr.s_addr=inet_addr(ip.c_str());

        if(connect(sock,(sockaddr*)&server,sizeof(server))==0)
        {
            return true;
        }
        return false;
    }
    ~Sock(){}
private:
    int _listenSock;
};
